<template>
    <el-main>
      <!-- 查询条件 -->
      <div style="overflow: hidden; ">
        <div style="float: left;">
          <el-form
            :model="searchModel"
            ref="searchForm"
            label-width="80px"
            :inline="true"
            size="small"
          >
            <el-form-item>
            <el-input v-model="searchModel.bbmc" placeholder="请输入报表名称" />
            </el-form-item>
            <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-search"
                @click="search(pageNo, pageSize)"
                >查询</el-button
            >
            <el-button icon="el-icon-refresh-right" @click="resetValue()"
                >重置</el-button
            >
            
            </el-form-item>
          </el-form>
        </div>

        <div style="float: right;">
            <el-button
            type="success"
            icon="el-icon-plus"
            @click="openAddWindow()"
            >新增</el-button>
        </div>
      </div>
      <!-- 数据表格 -->
      <el-table
        :data="dtbbList"
        :height="tableHeight"
        border
        stripe
        style="width: 100%; margin-bottom: 10px"
      >
        <el-table-column prop="bbdm" label="报表代码" align="center"></el-table-column>
        <el-table-column prop="bblx" label="报表类型" align="center"></el-table-column>
        <el-table-column prop="bbmc" label="报表名称" align="center" width="600"></el-table-column>
        <el-table-column label="操作" align="center" width="500">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑
            </el-button>   
            <el-button
              icon="el-icon-setting"
              type="primary"
              size="small"
              @click="selectZd(scope.row)"
              >选择字段
            </el-button>
            <el-button
              icon="el-icon-view"
              type="primary"
              size="small"
              @click="handleCheck(scope.row)"
              >预览
            </el-button>
            <el-button
              icon="el-icon-download"
              type="primary"
              size="small"
              @click="downloadExcel(scope.row)"
              >下载
            </el-button>
            <el-button
              icon="el-icon-delete"
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页工具栏 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="10"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加和修改角色窗口 -->
      <system-dialog
        :title="bbmbDialog.title"
        :visible="bbmbDialog.visible"
        :width="bbmbDialog.width"
        :height="bbmbDialog.height"
        @onClose="onClose"
        @onConfirm="onConfirm"
        >
        <div slot="content">
            <el-form
            :model="bbmb"
            ref="bbmbForm"
            :rules="rules"
            label-width="80px"
            :inline="false"
            size="small"
            >
            <el-form-item label="报表代码" prop="bbdm">
                <el-input v-model="bbmb.bbdm"></el-input>
            </el-form-item>
            <el-form-item label="报表类型" prop="bblx">
                <el-input v-model="bbmb.bblx"></el-input>
            </el-form-item>
            <el-form-item label="报表名称" prop="bbmc">
                <el-input v-model="bbmb.bbmc"></el-input>
            </el-form-item>
            </el-form>
        </div>
      </system-dialog>
      <!--选择字段窗口-->
      <el-dialog title="选择字段" :visible.sync="dialogVisible" width="40%">

        <el-form :inline="true" ref="bbform" :model="bbform">
            <el-form-item label="表名">
                <el-select v-model="bbform.id" placeholder="请选择" @change="changeSelect">
                <el-option
                    v-for="(item,index) in bbList"
                    :key="item.id"
                    :label="item.zdbt"
                    :value="item.id"
                />
                </el-select>

            </el-form-item>
            <el-form-item label="字段">
                <el-select v-model="bbform.zd" multiple :clearable="true" placeholder="请选择" @change="changeSelectZd">
                <el-option
                    v-for="(item,index) in zdList"
                    :key="index.id"
                    :label="item.zdbt"
                    :value="item.id"
                />
                </el-select>
            </el-form-item>
        </el-form>

        <el-collapse accordion @change="handleChange">
            <el-collapse-item v-for="(item,index) in afterList" :key="item.id" :title=item.zdbt>
                <div>
                    <el-form :inline="true" :model="infoForm" class="demo-form-inline" ref="infoForm" label-position="left" label-width="80px">
                        <el-row>
                            <el-col :span="12">
                            <el-form-item label="上级字段:">
                                <el-select v-model="infoForm.pid" :clearable="true" placeholder="请选择" @change="changeSelectSjzd">
                                <el-option
                                    v-for="(item,index) in sjzdList"
                                    :key="index.id"
                                    :label="item.lmc"
                                    :value="item.id"
                                />
                                </el-select>
                            </el-form-item>
                            </el-col>
                            <el-col :span="12">
                            <el-form-item label="所占格数:">
                                <el-input v-model="infoForm.szgs" placeholder="请输入"></el-input>
                            </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                            <el-form-item label="列序号:">
                                <el-input v-model="infoForm.lxh" placeholder="请输入"></el-input>
                            </el-form-item>
                            </el-col>
                            <el-col :span="12">
                            <el-form-item label="列名称:">
                                <el-input v-model="infoForm.lmc" placeholder="请输入"></el-input>
                            </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitInfo()">确 定</el-button>
                    </div>
                    

                </div>
                
            </el-collapse-item>
        </el-collapse>

        <span slot="footer" class="dialog-footer">
            <el-button @click="close()">取 消</el-button>
            <el-button type="primary" @click="submit()">确 定</el-button>
        </span>
      </el-dialog>

      <!--预览窗口-->
      <el-dialog :visible.sync="previewFile" width="1000px">
        <div class="tablestyle" id="table" >
            <table border="1" v-if="tableau" style="border-collapse: collapse">
            <tr v-for="(item, index) in tableau" :key="index">
                <td v-for="(item1, index1) in item" :key="index1">{{ item1 }}</td>
            </tr>
            </table>
        </div>
      </el-dialog>
    </el-main>
  </template>
  
  <script>
  import axios from "axios";
  import XLSX from 'xlsx';
  import dtbbApi from '@/api/dtbb/bbmb';
  import sjzdApi from '@/api/dtbb/sjzd';
  import infoApi from '@/api/dtbb/info';
  import { getToken } from "@/utils/auth";
  import SystemDialog from "@/components/system/SystemDialog.vue";

  // 导入末级节点脚本
  import leafUtils from "@/utils/leaf";
  
  export default {
    name: "dtbbList",
    components: { SystemDialog },
    data() {
      return {
        //查询条件
        searchModel: {
          bbmc: "",
          pageNo: 1,
          pageSize: 10,
        },
        dtbbList: [], //数据列表
        tableHeight: 0, //表格高度
        pageNo: 1, //当前页码
        pageSize: 10, //每页显示数量
        total: 0, //总数量
        rules: {
          bbdm: [
            { required: true, trigger: "blur", message: "请输入报表代码" },
          ],
          bblx: [
            { required: true, trigger: "blur", message: "请输入报表类型" },
          ],
          bbmc: [
            { required: true, trigger: "blur", message: "请输入报表名称" },
          ],
        },
        current:'',//当前行
        //添加和修改角色窗口属性
        bbmbDialog: { title: "", visible: false, height: 230, width: 500 },
        //角色对象
        bbmb: {
          id: "",
          bbdm: "",
          bblx: "",
          bbmc: "",
        },
        //分配权限窗口属性
        dialogVisible: false,
        bbform:{
            id:'',
            zd:'',
        },
        //下拉框列表数据
        bbList: [],
        zdList: [],
        sjzdList: [],
        //选择字段的对象list
        afterList:[],
        //tia
        infodata:'',
        //
        infoForm:{
            bbid:'',
            cj:'',
            pid:'',
            szgs:'1',
            lxh:'',
            lmc:'',
        },
        //预览
        previewFile:false,
        workbook:'',
        cardActive:'',
        tableau:'',
      };
    },
    methods: {
      /*** 查询 */
      async search(pageNo = 1, pageSize = 10) {
        this.searchModel.pageNo = pageNo; //当前页码
        this.searchModel.pageSize = pageSize; //每页显示数量
        //发送查询请求
        let res = await dtbbApi.getList(this.searchModel);
        //执行成功
        if (res.success) {
          console.log(res.data);
          //报表列表
          this.dtbbList = res.data.records;
          //总数量
          this.total = res.data.total;
        }
      },
      /*** 重置查询条件 */
      resetValue() {
        //清空查询条件
        this.searchModel.bbmc = "";
        //重新查询
        this.search();
      },
      /*** 打开添加窗口 */
      openAddWindow() {
        this.$resetForm("bbmbForm", this.bbmb); //清空表单数据
        this.bbmbDialog.title = "新增报表模板"; //设置窗口标题
        this.bbmbDialog.visible = true; //显示窗口
      },
      /**窗口取消 */
      onClose() {
        this.bbmbDialog.visible = false;
      },
      /**窗口确认 */
      onConfirm() {
        //表单验证
        this.$refs.bbmbForm.validate(async (valid) => {
          if (valid) {
            let res = null;
            //判断角色ID是否为空
            if (this.bbmb.id === "") {
              //新增 //发送添加请求
              res = await dtbbApi.add(this.bbmb);
              console.log("新增请求", res);
            } else {
              console.log(this.bbmb);
              //发送修改请求
              res = await dtbbApi.update(this.bbmb);
              console.log(res);
            }
            //判断是否成功
            if (res.success) {
              this.$message.success(res.message); //刷新
              this.search(this.pageNo, this.pageSize); //关闭窗口
              this.bbmbDialog.visible = false;
            } else {
              this.$message.error(res.message);
            }
          }
        });
      },
      /*** 打开编辑窗口 */
      handleEdit(row) {
        //数据回显
        this.$objCopy(row, this.bbmb); //将当前编辑的数据复制到role对象中 //设置窗口标题
        this.bbmbDialog.title = "编辑报表模板"; //显示编辑角色窗口
        this.bbmbDialog.visible = true;
      },
      /*** 删除 */
      async handleDelete(row) {
          //确认是否删除
          let confirm = await this.$myconfirm("确定要删除该数据吗?");
          if (confirm) {
            //发送删除请求
            let res = await dtbbApi.delete({ id: row.id });
            //判断是否成功
            if (res.success) {
              //成功提示
              this.$message.success(res.message);
              //刷新
              this.search(this.pageNo, this.pageSize);
            } else {
              //失败提示
              this.$message.error(res.message);
            }
          }
      },

      /**打开选择字段窗口 */
      async selectZd(row){
        this.current = row;
        this.dialogVisible = true;
        let res = await sjzdApi.getList({lx:0});
        //执行成功
        if (res.success) {
          console.log(res.data);
          this.bbList = res.data.records;
        }
      },
      /**下拉框数据联动 */
      async changeSelect() {
        // 清空字段内容
        this.bbform.zd = ''
        // 查出所选表对应的所有字段
        let res = await sjzdApi.getList({lx:1,pid:this.bbform.id});
        //执行成功
        if (res.success) {
          console.log(res.data);
          this.zdList = res.data.records;
        }
      },
      async changeSelectZd(val){
        console.log(val);

        var arr=[];
        for(var i = 0 ; i < val.length; i++){ 
            let obj={}
            obj= this.zdList.find((item)=>{
                return item.id === val[i];
            });
            console.log(obj);
            arr.push(obj);
            
        }
        this.afterList = arr;
        
        console.log(this.afterList);

        let res = await infoApi.getList({bbid:this.current.id});
        //执行成功
        if (res.success) {
          console.log('info'+JSON.stringify(res.data.records));
          this.sjzdList = res.data.records;
        }
      },
      changeSelectSjzd(val){
        console.log(val);
        if(val==''){
            this.infoForm.cj = 1
        }else{
            console.log(this.infoForm.pid);
        let obj={}
        obj= this.sjzdList.find((item)=>{
            return item.id === val;
        });
        console.log('cj'+obj.cj);
        this.infoForm.cj = obj.cj+1;
        }
        
      },
      handleChange(){
        this.$resetForm("infoForm", this.infoForm);
      },
      async submitInfo(){
        if(this.infoForm.pid ===''){
            this.infoForm.pid ='0';
        }
        this.infoForm.bbid = this.current.id;
        console.log('form'+JSON.stringify(this.infoForm));
        let res = await infoApi.add(this.infoForm);

        console.log(res)
        //判断是否成功
        if (res.success) {
            this.$message.success(res.message);
        } else {
            console.log(res)
            this.$message.error(res.message);
        }
      },
      /**关闭窗口 */
      close(){
        this.bbform.id = '';
        this.bbform.zd = '';
        this.afterList =[];
        this.dialogVisible = false;
        this.$resetForm("infoForm", this.infoForm);
      },
      /**选择字段确认按钮 */
      async submit(){
        this.dialogVisible = false;
        console.log(this.bbform.zd);

        // let res = await infoApi.add();
        // //执行成功
        // if (res.success) {
        //   this.$message.success(res.message);
        // }
      },
      //报表预览
      handleCheck(row){
        axios({ 
            method: "get",
            responseType: "arraybuffer", // 预览arraybuffer，下载：blob
            url:"http://47.108.251.250:3296/api/dtbb/DownloadMyExcel?token=" + getToken() + '&bbdm=' + row.bbdm,
        })
        .then((res) => {
            console.log(res); // 图一
            let data = new Uint8Array(res.data); //
            let workbook = XLSX.read(data, { type: "array" });
            console.log('workbook'+workbook);
            let sheetNames = workbook.SheetNames; // 工作表名称集合
            console.log(sheetNames);
            this.workbook = workbook;        
            this.cardActive = sheetNames[0];
            console.log('cardActive'+this.cardActive);
            this.getTable(sheetNames[0]);
            this.previewFile = true;
        })
        .catch((error) => {
            this.previewFile = false;
            this.$message.error("预览失败");
        });
      },
      getTable(sheetName) {
        var worksheet = this.workbook.Sheets[sheetName];
        console.log('worksheet'+JSON.stringify(worksheet));
        this.tableau = XLSX.utils.sheet_to_json(worksheet, {
            header: 1,
            defval: "",
        }); // 直接v-for循环
        console.log(this.tableau);
      },
      //报表下载
      downloadExcel(row){
        window.open("http://47.108.251.250:3296/api/dtbb/DownloadMyExcel?token=" + getToken() + '&bbdm=' + row.bbdm);

      },

      /*** 当每页数量发生变化时触发该事件 */
      handleSizeChange(size) {
        this.pageSize = size;
        //将每页显示的数量交给成员变量
        this.search(this.pageNo, size);
      },
      /*** 当页码发生变化时触发该事件 */
      handleCurrentChange(page) {
        this.pageNo = page;
        //调用查询方法
        this.search(page, this.pageSize);
      },

    },
    //初始化时调用
    created() {
      this.search();
    },
    //挂载后调用
    mounted() {
      this.$nextTick(() => {
        this.tableHeight = window.innerHeight - 220;
      });
    },
  };
  </script>
  
  <style lang="scss" scoped>
  
  .tablestyle{
      display: flex;
      justify-content: center;
      align-items: center;
}

.abow_dialog {
    display: flex;
    justify-content: center;
    align-items: Center;
    overflow: hidden;
    .el-dialog {
        margin: 0 auto !important;
        height: 90%;
        overflow: hidden;
        .el-dialog__body {
            position: absolute;
            left: 0;
            top: 54px;
            bottom: 0;
            right: 0;
            padding: 0;
            z-index: 1;
            overflow: hidden;
            overflow-y: auto;
        }
    }
}
</style>
  